<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<el-radio-group v-model="viewType" size="small" class="item-gap">
						<el-radio-button label="listView">
							<span class="el-icon-c-scale-to-original"></span>
							<span>列表</span>
						</el-radio-button>
						<el-radio-button label="chartView">
							<span class="el-icon-s-data"></span>
							<span>图表</span>
						</el-radio-button>
					</el-radio-group>
					<!--<div class="item-gap"><el-button icon="el-icon-back" size="small" type="small" plain @click="onBackBtn">返回上一页</el-button></div>-->
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<div><el-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onReportBtn">导出</el-button></div>
					<jk-date-picker v-model="searchParams.belongDate" size="small" type="daterange" style="width: 280px;" :picker-options="pickerOptions" value-format="yyyy-MM-dd" placeholder="选择日期" class="search-bar-item-size1 item-gap"></jk-date-picker>
					<jk-select v-model="searchParams.workshopId" clearable placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange">
					</jk-select>
					<jk-select v-model="searchParams.processCode" value-key-name="code" :option-list="garbledProcess" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<el-select v-model="searchParams.shiftId" clearable placeholder="班次" size="small" class="search-bar-item-size1 margin-5-0 item-gap">
						<el-option v-for="item in shiftList" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
					<jk-search-input v-model="searchParams.machineCode" placeholder="设备编号" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @change="onSearchBtn" @keyup.enter.native="onSearchBtn" />
					<jk-search-button class="" @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<listView
				:is="viewType"
				ref="exportTotalUse"
				:loading="tableLoading"
				:search-params="searchParams"
				:table-data="tableData"
				:height="tableHeight + 20"
				@getListRequest="getListRequest"
			></listView>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="searchParams.count"
					@on-change="onPage"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { formatDate, formatTime, pageConfig } from '/src/utils/jk/jk-tool';
    import permissionMixin from '../../../mixins/permission-mixin';
    import { getInfo } from '../../../api/login';
    import listView from './components/list-view';
    import chartView from './components/chart-view';
    import scheduleShift from '../scheduleShiftProductionReport/scheduleShift';
    import {
        iotCollectDataCountPage,
        iotCollectDataCountExportExcel
    } from '../../../api/production/frontGroupYieldStatistics';
    import { workforceManagementShiftGetByTime, workforcemanagementShiftPage } from '@/api/schedule/shift';
    import { systemUserColumnConfigGet } from '../../../api/system/column-config';
    export default {
        name: 'ScheduleShiftProductionReportRecord',
        mixins: [permissionMixin, calHeight, scheduleShift],
        components: {
            listView,
            chartView
        },
        data() {
            return {
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                tableColumnList: [],
                prefix: '',
                viewType: 'listView',
                processList: [],
                workshopList: [],
                garbledProcess: [],
                shiftList: [],
                dataId: null,
                tableLoading: false,
                exportLoading: false,
                tableData: [],
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    machineCode: null,
                    processCode: '',
                    belongDate: [],
                    shiftId: '',
                    workshopId: null
                }
            };
        },
        methods: {
            onPage(e, size) {
                this.searchParams.pageNo = e;
                this.searchParams.pageSize = size;
                this.getListRequest();
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                iotCollectDataCountPage(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.searchParams.count = res.data.count;
                    }
                });
            },
            onWorkshopChange(val) {
                this.$set(this.searchParams, 'shiftId', '');
                this.$set(this.searchParams, 'processCode', '');
                if (!this.searchParams.workshopId) {
                    this.shiftList = [];
                    this.garbledProcess = [];
                } else {
                    this.getShiftListRequest();
                    this.getProcessData(val);
                }
            },
            getProcessData(val) {
                this.garbledProcess = [];
                this.processList.forEach(y => {
                    if (val === y.workshopId) {
                        this.garbledProcess.push(y);
                    }
                });
            },
            // 当前班次信息
            getScheduleShift() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                delete params.shiftId;
                delete params.count;
                delete params.yarnCount;
                delete params.belongDate;
                delete params.groupId;
                delete params.processCode;
                params.belongTime = formatTime(Date.now());
                return workforceManagementShiftGetByTime(params).then(res => {
                    if (res.data.status === 200) {
                        this.$set(this.searchParams, 'shiftId', res.data.res.currentShiftInfo && res.data.res.currentShiftInfo.id ? res.data.res.currentShiftInfo.id : null);
                        let timeHorizon = [];
                        if (res.data.res && res.data.res.currentShiftInfo && res.data.res.currentShiftInfo.belongDate) {
                            timeHorizon = [res.data.res.currentShiftInfo.belongDate, res.data.res.currentShiftInfo.belongDate];
                        } else {
                            timeHorizon = [formatDate(Date.now()), formatDate(Date.now())];
                        }
                        if (this.searchParams.belongDate.length === 0) {
                            this.searchParams.belongDate = timeHorizon;
                        }
                    }
                });
            },
            // 获取所有班次
            getShiftListRequest() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                delete params.pageNo;
                delete params.pageSize;
                delete params.shiftId;
                delete params.count;
                delete params.yarnCount;
                delete params.belongDate;
                delete params.processCode;
                params.auditState = 1;
                return workforcemanagementShiftPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => {
                    return v[j];
                }));
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return iotCollectDataCountPage(params).then(res => {
                        if (res.data.status === 200) {
              import('@/vendor/Export2Excel').then(excel => {
                const tHeader = this.tableColumnList.map(x => x.title);
                const filterVal = this.tableColumnList.map(x => x.keyName);
                const list = JSON.parse(JSON.stringify(res.data.res)).map(item => {
                  return item;
                });
                // 合计项
                const totalItem = {};
                filterVal.forEach((x, idx) => {
                  totalItem[x] = this.$refs.exportTotalUse.$refs.frontGroupSalaryMonthReportTable.$refs.xTable.getTableData().footerData[0][idx];
                });
                list.push(totalItem);
                const data = list.map(v => filterVal.map(j => {
                  return v[j];
                }));
                excel.export_json_to_excel({
                  header: tHeader,
                  data,
                  filename: `${this.$route.meta.title}`,
                  autoWidth: true,
                  bookType: 'xlsx'
                });
              });
                        }
                    });
                }).catch(() => {});
            },
            getMenuColumnListRequest() {
                return systemUserColumnConfigGet({ path: 'scheduleShiftProductionReportRecord', filterShow: true }).then(res => {
                    if (res.data.status === 200) {
                        this.tableColumnList = res.data.res.columnConfigList && res.data.res.columnConfigList.length ? res.data.res.columnConfigList[0].itemList : [];
                    }
                });
            },
            async getDependentData() {
                this.processList = this.$store.state.user.userProcess.processList;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                await this.getMenuColumnListRequest();
                if (!this.searchParams.workshopId) {
                    this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                }
                if (!this.searchParams.processCode) {
                    this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode || '');
                }
                // if (this.searchParams.belongDate.length === 0) {
                //     this.$set(this.searchParams, 'belongDate', [formatDate(Date.now()), formatDate(Date.now())]);
                // }
                await this.getShiftListRequest();
                this.getProcessData(this.$store.state.user.userWorkshop.defaultWorkshopId);
                await this.getScheduleShift();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped>
</style>
